<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ClassBaseInfoTeacher;
use App\Models\UserSubscribe;
use App\Services\Admin\ClassBaseTime;
use App\Services\Admin\Classroom;
use App\Services\Admin\Index;
use App\Services\Admin\Reservation;
use App\Services\Admin\ClassQuarterly;
use App\Services\Admin\Store;
use App\Services\Admin\ClassBaseNumbering;
use App\Http\Requests\Admin\ReservationController\doRule;
use App\Http\Requests\Admin\ReservationController\classBaseInfoTeacherDoRule;
use App\Services\Admin\Teacher;
use App\Services\Admin\User;
use App\Services\Admin\UserRankExp;
use App\Services\Admin\UserSubscribeService;
use App\Services\Api\UserIntegralServices;
use phpDocumentor\Reflection\Types\Self_;


class ReservationController extends Controller
{
    public function index()
    {

        $result = [
            'user_rank'=>UserRankExp::level(),
            'result' => Reservation::lists()->paginate(15),
            'select_store' => Store::where_lists(),
            'week'=> ClassBaseTime::week_result(),
            'store_id' => \request()->get('store_id'),
            'user_rank_id' => \request()->get('user_rank_id'),
            'class_base_id'=>\request()->get('class_base'),
            'classroom_id'=>\request()->get('classroom'),
            'teacher_id'=>\request()->get('teacher'),
            'week_get'=>request()->get('week')
        ];

        return view('admin.reservation.index', $result);

    }

    public function sign_code($id, $time)
    {
        //查询已签到的会员
        $user_id = Index::user_train($id, $time)->pluck('user_id')->toArray();

        $class_base_info = Reservation::lists()->where('id', $id)->first()->toArray();
        $class_base_info['teacher'] = Reservation::class_bass_info_teacher_arr($class_base_info['class_base_info_teacher']);

        $result = [
            'liantu_ar'=>Reservation::info($id)->liantu_qr,
            'user_lists'=>User::lists()->whereIn('id',$user_id)->get(),
            'sear_value'=>request()->get('sear_value'),
            'class_base_info'=>$class_base_info,
            'id'=>$id,
            'time'=>$time,
        ];

        return view('admin.reservation.sign_code', $result);
    }

    //簽到打開(作废)
    public function sign_lists($class_bass_info_id, $time)
    {
        //查询已签到的会员
        $lists = UserSubscribeService::lists($class_bass_info_id, $time);

        $result = [
            //'result'=>User::lists()->whereNotIn('id',$user_id)->paginate(15),
            'sear_value'=>request()->sear_value??'',
            'class_bass_info_id'=>$class_bass_info_id,
            'time'=>$time
        ];

        return view('admin.reservation.sign_lists',$result);
    }

    public function home_lists($day)
    {
        request()->day = $day;

        $result = [
            'result' => Reservation::lists()->paginate(15),
        ];

        return view('admin.reservation.home_lists',$result);
    }

    public function home_add($class_classroom_id, $time)
    {
        //查询老师
        $booked = Reservation::lists_add($class_classroom_id, $time)->orderBy('class_time', 'asc')->get()->toArray();

        foreach ($booked as $k=>$v) {
            $booked[$k]['teacher'] = Reservation::class_bass_info_teacher_arr($v['class_base_info_teacher']);
        }

        $store_id = Classroom::info($class_classroom_id)->store_id??0;

        //查询老师
        $teacher_id = Teacher::lists()->where('store_id', $store_id)->select('teacher_name','id')->get();

        $result = [
            'select_store'=>Store::where_lists(),
            'select_class_base_numbering'=>ClassBaseNumbering::lists()->get(),
            'class_quarterly'=>ClassQuarterly::lists(1)->get(),
            'week_lists'=> ClassBaseTime::week_result(),
            'home' => Reservation::home($class_classroom_id, $time),
            'booked'=> $booked,
            'store_id' => $store_id??0,
            'classroom_id'=>$class_classroom_id,
            'time'=>$time,
            'class_base_id'=>'',
            'class_base_numbering_id'=>'',
            'teacher_id'=>$teacher_id,
        ];

        return view('admin.reservation.home_add',$result);
    }

    public function home_edit($class_classroom_id, $time, $id)
    {
        $reservation_lists = Reservation::lists()->where([['id', $id]])->first()->toArray();

        $open_an_appointment_result = $reservation_lists['class_base_info_suspension']??[];

        $open_an_appointment = Reservation::current_control_time($open_an_appointment_result, $time);

        $time_start = explode(":",$reservation_lists['class_time']['time_start']);

        $time_end = explode(":",$reservation_lists['class_time']['time_end']);

        //查询老师
        $booked = Reservation::lists_add($class_classroom_id, $time)->orderBy('class_time', 'asc')->get()->toArray();

        foreach ($booked as $k=>$v) {
            $booked[$k]['teacher'] = Reservation::class_bass_info_teacher_arr($v['class_base_info_teacher']);
        }

        $reservation_lists['teacher'] = Reservation::class_bass_info_teacher_arr($reservation_lists['class_base_info_teacher']);

        $result = [
            'select_store'=>Store::where_lists(),
            'select_class_base_numbering'=>ClassBaseNumbering::lists()->get(),
            'class_quarterly'=>ClassQuarterly::lists(1)->get(),
            'week_lists'=> ClassBaseTime::week_result(),
            'home' => Reservation::home($class_classroom_id, $time),
            'booked'=> $booked,
            'store_id' => Classroom::info($class_classroom_id)->store_id??0,
            'classroom_id'=>$class_classroom_id,
            'id'=>$id,
            'time'=>$time,
            'reservation_lists'=>$reservation_lists,
            'class_base_id'=>$reservation_lists['class_base_id'],
            'teacher_id'=>$reservation_lists['teacher']['id']??0,
            'teacher_name'=>$reservation_lists['teacher']['teacher_name']??'',
            'time_start_hour'=>$time_start[0],
            'time_start_minute'=>$time_start[1],
            'time_end_hour'=>$time_end[0],
            'time_end_minute'=>$time_end[1],
            'open_an_appointment'=>$open_an_appointment,
            'class_base_numbering_id'=>$reservation_lists['class_base']['numbering']['id']??0,
            'user_rank'=>UserRankExp::level(),
        ];

        return view('admin.reservation.home_add',$result);
    }

    /**
     * 预约用户列表
     */
    public function home_reservation_lists($class_base_info_id, $time, $camp)
    {
        //查询已预约过的用户，并且排除掉
        $user_id = Reservation::user_subscribe($class_base_info_id, $time)->whereIn('subscribe_status',[1,2,5,7])->pluck('user_id')->toArray();

        request()->offsetSet('day', $time);
        $class_base_info = Reservation::lists()->where('id', $class_base_info_id)->first()->toArray();

        $class_base_info['teacher'] = Reservation::class_bass_info_teacher_arr($class_base_info['class_base_info_teacher']);

        $result = [
            'result'=>User::lists()->whereNotIn('id', $user_id)->paginate(15),
            'sear_value'=>request()->sear_value??'',
            'class_base_info'=>$class_base_info,
            'time'=>$time,
            'class_base_info_id'=>$class_base_info_id,
            'camp'=>$camp
        ];

        return view('admin.reservation.home_reservation_lists',$result);
    }

    /**
     * 单节课预约动作
     */
    public function home_reservation_do($class_base_info_id, $time, $user_id, $camp)
    {

        $reservation_info = Reservation::lists()->where('id', $class_base_info_id)->first();

        //预约成功或者上课完成
        $user_subscribe = Reservation::user_subscribe($class_base_info_id, $time)->where('user_id', $user_id)->whereIn('subscribe_status',['2','5'])->get();

        if($user_subscribe->isNotEmpty())return self::fail('该用户已预约过了');

        $class_time = explode("~",$reservation_info->class_time);

        if(time() > strtotime("{$time} $class_time[0]"))return self::fail('已開課,不能預約!');

        if($reservation_info->quarterly->end_time < date("Y-m-d H:i:s"))return self::fail('不在上课季节!');

        $start_time = "{$time} 00:00:00";
        $end_time = "{$time} 23:59:59";

        $class_subscribe_number = (new UserSubscribe)->ClassSubscribeNumber([$class_base_info_id], $start_time, $end_time);

        if(!isset($class_subscribe_number[$class_base_info_id])){
            //return self::fail('参数有误!');
        }else{
            if($class_subscribe_number[$class_base_info_id] >= $reservation_info->class_number_people)return self::fail('已经满人了!');
        }

        $class_bass_info_teacher_arr = Reservation::class_bass_info_teacher_result($class_base_info_id)->get()->toArray();

        $teacher = Reservation::class_bass_info_teacher_arr($class_bass_info_teacher_arr, $time);

        if(empty($teacher['id']))return self::fail('该时间没老师上课!');

        $user_integral_services = new UserIntegralServices();

        $available_integral = $user_integral_services->available_integral($user_id);

        if ($available_integral < ($reservation_info->class_base->class_price)) return self::fail('積分不足');

        $end_time_string = "{$class_time[0]}-{$class_time[1]}";

        $use_integral_msg = [
            '后台帮忙预约',
            "-{$reservation_info->class_base->class_price}分",
            $time,
            $end_time_string,
            $reservation_info->class_base->class_name
        ];

        //扣减积分
        $msg = implode("/",$use_integral_msg);

        $refund = $user_integral_services->use_integral($user_id, $reservation_info->class_base->class_price, $msg);

        $insert['user_id'] = $user_id;
        $insert['class_base_id'] = $reservation_info->class_base->id;
        $insert['class_name'] = $reservation_info->class_base->class_name;
        $insert['store_id'] = $reservation_info->store_id;
        $insert['store_id'] = $reservation_info->store_id;
        $insert['store_name'] = $reservation_info->store->store_name;
        $insert['class_classroom_id'] = $reservation_info->classsroom->id;
        $insert['class_classroom_name'] = $reservation_info->classsroom->numbering;
        $insert['class_base_info_id'] = $class_base_info_id;
        $insert['teacher_id'] = $teacher['id'];
        $insert['teacher_name'] = $teacher['teacher_name'];
        $insert['use_integral'] = $reservation_info->class_base->class_price;
        $insert['buy_type'] = 1;
        $insert['is_tutoring'] = $camp;
        $insert['class_info'] = json_encode($reservation_info->class_base);

        if($camp == 1){
            $subscribe_status = 7;
        }else{
            $subscribe_status = 2;
        }

        $insert['subscribe_status'] = $subscribe_status;
        $insert['remarks'] = '后台帮忙预约';

        $class_time_string = explode("~", $reservation_info->class_time);

        $insert['class_time'] = "{$time} ".$class_time_string[0];
        $insert['end_time'] = "{$time} ".$class_time_string[1];
        $insert['is_coupon'] = 2;

        (new UserSubscribe())->create($insert);

        return self::success();
    }


    /**
     * 用於課程添加列表的（作廢）
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function add()
    {

        $result = [
            'select_store'=>Store::where_lists(),
            'week_lists'=> ClassBaseTime::week_result(),
            'select_id' => '',
            'class_base_id'=>'',
            'classroom_id'=>'',
            'teacher_id'=>'',
            'base_time_id'=>'',
        ];

        return view('admin.reservation.edit',$result);

    }

    public function do(doRule $request)
    {
        if ($request->ajax()) {

            $input = $request->all();

            if(empty($input['id'])) {

                if (Reservation::is_appointment_number()) return self::fail('该时间段已被占用');

                if($input['is_display'] == '1' || $input['open_an_appointment'] == '1'){
                    if(empty($input['teacher_id'])){
                        return self::fail('安排了老師上課在開放預約');
                    }
                }

                Reservation::add($input);

            }else{

                $reservation_lists = Reservation::class_bass_info_teacher_result($input['id'])->get()->toArray();

                $is_common = array_column($reservation_lists,'is_common');

                if($input['is_display'] == '1')if(!in_array('1',$is_common))return self::fail('安排了老師上課在開放預約');
                if($input['open_an_appointment'] == '1') {
                    $teacher = Reservation::class_bass_info_teacher_arr($reservation_lists, $input['time']);
                    if (empty($teacher['id'])) return self::fail('安排了老師上課在開放預約');
                }

                Reservation::edit($input['id'], $input);

            }

            return self::success([]);
        }
    }

    public function del($id)
    {

        Reservation::del($id);

        return self::success([]);

    }

    /**
     * 老师安排
     * @param $id
     */
    public function class_base_info_teacher($id)
    {
        $result = [
            'class_bass_info_teacher'=> Reservation::class_bass_info_teacher($id)->paginate(15),
            'class_bass_info'=>Reservation::lists()->where('id', $id)->first()->toArray(),
            'class_time'=>request()->get('class_time'),
            'teacher_name'=>request()->get('teacher_name'),
            'id'=>$id,
        ];

        return view('admin.reservation.class_base_info_teacher', $result);
    }

    public function class_base_info_teacher_del($id, $teacher_id)
    {
        Reservation::class_bass_info_teacher_del($id, $teacher_id);

        return self::success([]);
    }

    public function class_base_info_teacher_add($id)
    {
        $teacher_id = Reservation::class_bass_info_teacher($id)->pluck('teacher_id')->toArray();

        $class_bass_info_teacher = Teacher::lists()->whereNotIn('id', $teacher_id)->select('id','teacher_name')->get();

        $result = [
            'id'=>$id,
            'class_bass_info_teacher'=>$class_bass_info_teacher
        ];

        return view('admin.reservation.class_base_info_teacher_add', $result);
    }

    public function class_base_info_teacher_do(classBaseInfoTeacherDoRule $request)
    {
        $class_bass_info_teacher_do = Reservation::class_bass_info_teacher_do();

        if(!$class_bass_info_teacher_do['bool'])return self::fail($class_bass_info_teacher_do['message']);

        return self::success([]);
    }

    /**
     * 修改等级
     */
    public function class_base_info_edit_level()
    {
        $input = request()->all();

        $user_rank_id = null;

        if(!empty($input['user_rank_id'])) {
            if (is_array($input['user_rank_id'])) {
                $user_rank_id = implode(',', $input['user_rank_id']);
            }
        }

        Reservation::class_base_info_edit_level([$input['class_base_info_id']], $user_rank_id);

        return self::success([]);
    }
}
